package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.bean.ListNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/7/12.<br><br>
 *
 * 链表的中间结点
 */
public class Topic876 {

    public static void main(String[] args) {
        Topic876 instance = new Topic876();

        int[] array = new int[] {1,2,3,4,5};
        ListNode head = Util.createList(array);
        System.out.println(instance.middleNode(head).val);

        array = new int[] {1,2,3,4,5,6};
        head = Util.createList(array);
        System.out.println(instance.middleNode(head).val);
    }

    public ListNode middleNode(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }

        ListNode low = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            low = low.next;
            fast = fast.next.next;
        }

        return low;
    }
}
